﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace BDRUtils.Extensions
{
    public static class EnumerableExtensions
    {
        /// <summary>
        /// 集合是否为空
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsEmpty<T>(this IEnumerable<T> value) => (value?.Count() ?? 0) == 0;

        /// <summary>
        /// 集合是否不为空
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNotEmpty<T>(this IEnumerable<T> value) => (value?.Count() ?? 0) > 0;

        /// <summary>
        /// 获取不同的集合
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="source"></param>
        /// <param name="keySelector"></param>
        /// <returns></returns>
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }

        /// <summary>
        /// 集合分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static IEnumerable<T> Page<T>(this IEnumerable<T> value, int index, int size)
        {
            var start = Math.Max(index - 1, 0) * size;
            var result = value.Skip(start).Take(size);
            return result;
        }
    }
}
